package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.dto.ReportRecoderResponse;
import com.ugoodtech.mdcc.client.dto.ReportRecorder;
import com.ugoodtech.mdcc.client.service.ServiceReportRecorderService;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ServiceReportRecorderServiceImpl implements ServiceReportRecorderService {

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private ServiceReportHistoricalRecorderRepository serviceReportHistoricalRecorderRepository;

    /**
     * 获取处理记录
     *
     * @param reportId
     * @return
     */
    @Override
    public JsonResponse getRecorder(Long reportId, Long userId) {
        UserProfile userProfile = userProfileRepository.findByUserId(userId);
        List<Department> departmentList = userProfile.getDepartmentList();
        List<Long> ids = new ArrayList<>();
        for (Department department : departmentList) {
            ids.add(department.getId());
        }
        QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceReportRecorder.deleted.eq(false));
        builder.and(qServiceReportRecorder.enabled.eq(true));
        builder.and(qServiceReportRecorder.department.id.in(ids));
        builder.and(qServiceReportRecorder.stationReport.id.eq(reportId));
        return JsonResponse.successResponseWithData(serviceReportRecorderRepository.findAll(builder));
    }

    /**
     * 管理员获取跟进报告的部门列表
     */
    @Override
    public JsonResponse managerGetRecorder(Long reportId) {
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告");
        }
        QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceReportRecorder.deleted.eq(false));
        builder.and(qServiceReportRecorder.enabled.eq(true));
        builder.and(qServiceReportRecorder.stationReport.id.eq(reportId));
        List<ServiceReportRecorder> serviceReportRecorderList = (List<ServiceReportRecorder>) serviceReportRecorderRepository.findAll(builder);
        Map<Department, Integer> map = new HashMap<>();
        for (ServiceReportRecorder recorder : serviceReportRecorderList) {
            if (map.containsKey(recorder.getDepartment())) {
                continue;
            } else {
                map.put(recorder.getDepartment(), 1);
            }
        }
        List<ReportRecorder> reportRecorders = new ArrayList<>();
        for (Map.Entry<Department, Integer> entry : map.entrySet()) {
            Department department = entry.getKey();
            if (department != null) {
                ReportRecorder reportRecorder = new ReportRecorder();
                reportRecorder.setDeparmentId(department.getId());
                reportRecorder.setDistrict(department.getTotalName());
                reportRecorder.setReportId(reportId);
                if (department.getLeader() == null) {
                    reportRecorder.setName("还未指定负责人");
                } else {
                    UserProfile userProfile = userProfileRepository.findByUserId(department.getLeader().getId());
                    if (userProfile == null || StringUtils.isEmpty(userProfile.getRealName())) {
                        reportRecorder.setName("还未指定负责人");
                    } else {
                        reportRecorder.setName(userProfile.getRealName());
                    }
                }
                reportRecorders.add(reportRecorder);
            }
        }
//        String deparmentIds = stationReport.getDeparmentIds();
//        String[] deparmentIdArray = deparmentIds.split(",");
//
//        for (String id : deparmentIdArray) {
//            Department department = departmentRepository.findOne(Long.valueOf(id));
//            if (department != null) {
//                ReportRecorder reportRecorder = new ReportRecorder();
//                reportRecorder.setDeparmentId(department.getId());
//                reportRecorder.setDistrict(department.getTotalName());
//                reportRecorder.setReportId(reportId);
//                if (department.getLeader() == null) {
//                    reportRecorder.setName("还未指定负责人");
//                } else {
//                    UserProfile userProfile = userProfileRepository.findByUserId(department.getLeader().getId());
//                    if (userProfile == null || StringUtils.isEmpty(userProfile.getRealName())) {
//                        reportRecorder.setName("还未指定负责人");
//                    } else {
//                        reportRecorder.setName(userProfile.getRealName());
//                    }
//                }
//                reportRecorders.add(reportRecorder);
//            }
//        }
        return JsonResponse.successResponseWithData(reportRecorders);
    }

    @Override
    public JsonResponse getReportRecoder(Long deparmentId, Long reportId, Pageable pageable) {
        QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceReportRecorder.deleted.eq(false));
        builder.and(qServiceReportRecorder.enabled.eq(true));
        builder.and(qServiceReportRecorder.stationReport.id.eq(reportId));
        Sort sort = new Sort(Sort.Direction.ASC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ServiceReportRecorder> serviceReportRecorders = serviceReportRecorderRepository.findAll(builder, pageable);
        List<ReportRecoderResponse> recoderResponseList = responseVO(serviceReportRecorders);
        return JsonResponse.successResponseWithData(recoderResponseList);
    }

    @Override
    public JsonResponse getHistoricalReportRecoder(Long reportId, Pageable pageable) {
        QServiceReportHistoricalRecorder qServiceReportHistoricalRecorder = QServiceReportHistoricalRecorder.serviceReportHistoricalRecorder;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceReportHistoricalRecorder.deleted.eq(false));
        builder.and(qServiceReportHistoricalRecorder.enabled.eq(true));
        builder.and(qServiceReportHistoricalRecorder.stationReport.id.eq(reportId));
        Sort sort = new Sort(Sort.Direction.ASC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ServiceReportHistoricalRecorder> serviceReportHistoricalRecorders = serviceReportHistoricalRecorderRepository.findAll(builder, pageable);
        List<ReportRecoderResponse> recoderResponseList = responseHistoricalVO(serviceReportHistoricalRecorders);
        return JsonResponse.successResponseWithData(recoderResponseList);
    }

    private List<ReportRecoderResponse> responseHistoricalVO(Page<ServiceReportHistoricalRecorder> serviceReportHistoricalRecorders) {
        List<ReportRecoderResponse> recoderResponseList = new ArrayList<>();
        for (ServiceReportHistoricalRecorder recorder : serviceReportHistoricalRecorders) {
            ReportRecoderResponse response = new ReportRecoderResponse();
            response.setTime(recorder.getCreationTimeStr());
            response.setType(recorder.getType());
            response.setNote(recorder.getNote());
            String realName = "";
            if (recorder.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(recorder.getUser().getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    realName = userProfile.getRealName();
                }
            }
            response.setUserName(realName);
            recoderResponseList.add(response);
        }
        return recoderResponseList;
    }

    private List<ReportRecoderResponse> responseVO(Page<ServiceReportRecorder> serviceReportRecorders) {
        List<ReportRecoderResponse> recoderResponseList = new ArrayList<>();
        for (ServiceReportRecorder recorder : serviceReportRecorders) {
            ReportRecoderResponse response = new ReportRecoderResponse();
            response.setTime(recorder.getCreationTimeStr());
            response.setType(recorder.getType());
            response.setNote(recorder.getNote());
            String realName = "";
            String departmentName = "";
            if (recorder.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(recorder.getUser().getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    realName = userProfile.getRealName();
                    Department department = userProfile.getDepartmentList().get(0);
                    if (department != null) {
                        String value = department.getTotalName();
                        String[] values = value.split("-");
                        if (values.length != 0) {
                            departmentName = values[0];
                        }
                    }
                }
            }

            if (recorder.getDepartment() != null && StringUtils.isNotEmpty(recorder.getDepartment().getTotalName())) {
                departmentName = recorder.getDepartment().getTotalName();
                String[] values = departmentName.split("-");
                departmentName = values[0];
            }

            if (recorder.getNote().indexOf("确认的部门为") != -1) {
                response.setDepartmentName("系统管理员");
            } else {
                response.setDepartmentName(departmentName);
            }
            if (recorder.getUser().getId().equals(123L)) {
                response.setDepartmentName("系统管理员");
            }
            response.setUserName(realName);

            if (recorder.getType().equals("创建报告")) {
                response.setMsgStr(realName + "创建了报告");
            } else if (recorder.getType().equals("需其他部门后续跟进") || recorder.getType().equals("需其他部门跟进")) {
                response.setMsgStr(realName + "提交了常规服务报告，选择了：已完成，需其他部门跟进</br>需要跟进部门为:" + recorder.getNeedFollowDepartment());
            } else if (recorder.getType().equals("已确认")) {
                response.setType("审批跟进部门");
                if (StringUtils.isNotEmpty(recorder.getNeedFollowDepartment())) {
                    response.setMsgStr(realName + "更新了报告状态为:确认了需要跟进的部门</br>需要跟进部门为:" + recorder.getNeedFollowDepartment());
                } else if (StringUtils.isNotEmpty(recorder.getNote())) {
                    String note = recorder.getNote().replace("确认的部门为：", "");
                    response.setMsgStr(realName + "更新了报告状态为:确认了需要跟进的部门</br>需要跟进部门为:" + note);
                }
                if (StringUtils.isNotEmpty(recorder.getManageNote())) {
                    response.setNote(recorder.getManageNote());
                } else {
                    response.setNote("");
                }
            } else {
                String departmentStr = needFollowDepartment(recorder);
                if (recorder.getType().equals("需其他部门后续跟进")) {
                    response.setMsgStr(realName + "更新了报告状态为:" + recorder.getType() + "</br>需要跟进的部门为:" + departmentStr);
                } else {
                    response.setMsgStr(realName + "更新了报告状态为:" + recorder.getType());
                }
                response.setNote(recorder.getNote());
            }
            recoderResponseList.add(response);
        }
        return recoderResponseList;
    }

    //需要跟进的部门
    private String needFollowDepartment(ServiceReportRecorder reportRecorder) {
        StationReport stationReport = reportRecorder.getStationReport();
        String departmentIds = stationReport.getDeparmentIds();
        StringBuffer stringBuffer = new StringBuffer("");
        if (StringUtils.isNotEmpty(departmentIds)) {
            String[] ids = departmentIds.split(",");
            for (String id : ids) {
                Department department = departmentRepository.findOne(Long.valueOf(id));
                if (department != null && StringUtils.isNotEmpty(department.getTotalName())) {
                    stringBuffer.append(department.getTotalName() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }


}
